package com.bfly.mall.wechat.api;

import com.bfly.common.ResponseUtil;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.cache.EhCacheUtil;
import com.bfly.core.context.IpThreadLocal;
import com.bfly.core.security.Md5PwdEncoder;
import com.bfly.mall.user.entity.User;
import com.bfly.mall.user.enums.PlatformType;
import com.bfly.mall.user.service.IUserService;
import com.bfly.mall.wechat.minipro.dto.WeChatLoginResult;
import com.bfly.mall.wechat.minipro.dto.WeChatMiniProUserInfo;
import com.bfly.mall.wechat.minipro.dto.message.WeChatCancelSuccessMessage;
import com.bfly.mall.wechat.minipro.dto.message.WeChatPaySuccessMessage;
import com.bfly.mall.wechat.minipro.dto.message.WeChatRefundSuccessMessage;
import com.bfly.mall.wechat.minipro.dto.message.WeChatShipSuccessMessage;
import com.bfly.mall.wechat.minipro.service.WeChatMiniProAPi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 微信小程序Controller
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/3/25 0025
 */
@RestController
@RequestMapping(value = "/api/wechat")
public class WeChatMiniProController {

    @Autowired
    private IUserService userService;

    /**
     * 微信用户授权登录
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/11/12 14:27
     */
    @PostMapping(value = "/login")
    public void code2Session(HttpServletResponse response, @RequestBody WeChatMiniProUserInfo info, @RequestParam("code") String code) {
        synchronized (this.getClass()) {
            WeChatLoginResult result = WeChatMiniProAPi.code2Session(code);
            User user = userService.getUser(result.getOpenid());
            boolean exist = false;
            if (user == null) {
                // 新用户
                user = new User();
                user.setOpenId(result.getOpenid());
                user.setEnable(true);
                user.setPlatform(PlatformType.WECHAT_MINIPRO.getId());
                user.setCreateDate(new Date());
            } else {
                exist = true;
                user.setLastLoginDate(new Date());
                user.setLastLoginIp(IpThreadLocal.get());
            }

            user.setCity(info.getCity());
            user.setCountry(info.getCountry());
            user.setProvince(info.getProvince());
            user.setLanguage(info.getLanguage());

            user.setAvatarUrl(info.getAvatarUrl());
            user.setGender(info.getGender());
            user.setNickName(info.getNickName());

            if (exist) {
                userService.edit(user);
            } else {
                userService.save(user);
            }

            // 把小程序生成的session_key md5加密后返回给客户端
            // 客户端每次通信需要带上加密后的sessionId
            String sessionKey = new Md5PwdEncoder().encodePassword(result.getSession_key());

            // 缓存当前小程序授权通信的session_key 用于后面的业务解密用处
            EhCacheUtil.setData(EhCacheUtil.APPLET_SESSION_KEY_CACHE, sessionKey, result.getSession_key());

            // 缓存当前小程序授权用户对象
            EhCacheUtil.setData(EhCacheUtil.APPLET_USER_CACHE, sessionKey, user);

            ResponseUtil.writeJson(response, ResponseData.getSuccess(sessionKey));
        }
    }

    /**
     * 订单支付业务相关的模板信息
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/14 23:00
     */
    @GetMapping(value = "template/pay")
    public void orderPayBusinessMessageTemplate(HttpServletResponse response) {
        List<String> list = new ArrayList<>();
        list.add(new WeChatPaySuccessMessage().getTemplateId());
        list.add(new WeChatShipSuccessMessage().getTemplateId());
        ResponseUtil.writeJson(response, ResponseData.getSuccess(list));
    }

    /**
     * 订单取消业务相关的模板信息
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/14 23:03
     */
    @GetMapping(value = "/template/cancel")
    public void orderCancelBusinessMessageTemplate(HttpServletResponse response) {
        List<String> list = new ArrayList<>();
        list.add(new WeChatCancelSuccessMessage().getTemplateId());
        list.add(new WeChatRefundSuccessMessage().getTemplateId());
        ResponseUtil.writeJson(response, ResponseData.getSuccess(list));
    }

    /**
     * 获得小程序码
     *
     * @author andy_hulibo@163.com
     * @date 2020/12/20 13:37
     */
    @GetMapping(value = "/acode")
    public void getMiniProACode(HttpServletResponse response, @RequestParam("path") String path) {
        String aCode = WeChatMiniProAPi.getWxACode(path);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(aCode));
    }
}